package com.hzncc.flowable_diboot.controller.invoicemanage;

import com.diboot.core.util.V;
import com.diboot.core.util.S;
import com.diboot.core.util.ContextHolder;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.LabelValue;
import com.diboot.core.vo.Pagination;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.file.util.ExcelHelper;
import com.diboot.file.util.HttpHelper;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.hzncc.flowable_diboot.delivery.dto.DeliveryFormDTO;
import com.hzncc.flowable_diboot.delivery.excel.model.DeliveryFormExportModel;
import com.hzncc.flowable_diboot.delivery.vo.DeliveryFormVO;
import com.hzncc.flowable_diboot.dto.invoicemanage.InvoiceFormDTO;
import com.hzncc.flowable_diboot.excel.model.InvoiceFormExportModel;
import com.hzncc.flowable_diboot.vo.invoicemanage.InvoiceFormVO;
import com.hzncc.flowable_diboot.vo.invoicemanage.SyncInvoiceRegisterVO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.hzncc.flowable_diboot.entity.invoicemanage.InvoiceRegister;
import com.hzncc.flowable_diboot.service.invoicemanage.InvoiceRegisterService;
import com.hzncc.flowable_diboot.vo.invoicemanage.InvoiceRegisterDetailVO;
import com.hzncc.flowable_diboot.vo.invoicemanage.InvoiceRegisterListVO;
import com.hzncc.flowable_diboot.dto.invoicemanage.InvoiceRegisterDTO;

import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 开票登记 相关rest接口
* @author MyName
* @version 1.0
* @date 2024-11-06
* Copyright © MyCorp
*/
@Slf4j
@RequestMapping("/invoice-manage/invoice-register")
@BindPermission(name = "开票登记")
@RestController
public class InvoiceRegisterController extends BaseCrudRestController<InvoiceRegister> {

    @Autowired
    private InvoiceRegisterService invoiceRegisterService;

    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = "开票单报表导出", code = OperationCons.CODE_READ)
    @GetMapping("/invoice-forms-export")
    public JsonResult<?> getInvoiceFormsExport(InvoiceFormDTO queryDto,HttpServletResponse response) {
        List<String> columns = queryDto.getColumns();
        List<InvoiceFormVO> invoiceForms = invoiceRegisterService.getInvoiceForms(queryDto);
        List<InvoiceFormExportModel> invoiceFormExportModels = this.convertList(invoiceForms);
        ExcelHelper.exportExcel(response, "开票单报表.xlsx", InvoiceFormExportModel.class, columns, invoiceFormExportModels);
        return null;
    }

    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = "开票单报表查询", code = OperationCons.CODE_READ)
    @GetMapping("/invoice-forms")
    public JsonResult<?> getInvoiceForms(InvoiceFormDTO queryDto, Pagination pagination) {
        List<InvoiceFormVO> invoiceForms = invoiceRegisterService.getInvoiceForms(queryDto, pagination);
        return JsonResult.OK(invoiceForms).bindPagination(pagination);
    }

    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/get-invoice-codes")
    public JsonResult<Map<String,String>> getInvoiceCodeList(@RequestParam("registerType") String registerType) throws Exception {
        Map<String,String> result = invoiceRegisterService.getInvoiceCodeList(registerType);
        return JsonResult.OK(result);
    }

    /**
     * 打印回执单
     * @param invoiceRegisterIds
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @GetMapping("/print-receipt")
    public JsonResult<Serializable> printReceipt(HttpServletResponse response, @RequestParam List<String> invoiceRegisterIds) throws Exception {
        invoiceRegisterService.printReceipt(response,invoiceRegisterIds);
        return JsonResult.OK();
    }

    /**
     * sap开票数据同步（sap->crm）
     * @param syncInvoiceRegisterVO
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @PostMapping("/sync")
    public JsonResult<Serializable> syncInvoiceRegister(@RequestBody SyncInvoiceRegisterVO syncInvoiceRegisterVO) throws Exception {
        invoiceRegisterService.syncInvoiceRegister(syncInvoiceRegisterVO);
        return JsonResult.OK();
    }

    /**
    * 查询资源对象的列表VO记录
    * <p>
    * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
    * </p>
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<InvoiceRegisterListVO>> getListVOMapping(InvoiceRegisterDTO queryDto, Pagination pagination) throws Exception {
//        return super.getViewObjectList(queryDto, pagination, InvoiceRegisterListVO.class);
        List<InvoiceRegisterListVO> invoiceRegisterList = invoiceRegisterService.getPage(queryDto, pagination);
        return JsonResult.OK(invoiceRegisterList).bindPagination(pagination);
    }

    /**
    * 根据id查询资源对象的详情VO
    * @param id ID
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<InvoiceRegisterDetailVO> getDetailVOMapping(@PathVariable("id")String id) throws Exception {
//        InvoiceRegisterDetailVO detailVO = invoiceRegisterService.getViewObject(id, InvoiceRegisterDetailVO.class);
        InvoiceRegisterDetailVO detailVO = invoiceRegisterService.getDetail(id);
        return JsonResult.OK(detailVO);
    }

/**
    * 根据指定字段和值查询资源对象的详情VO
    * @param fieldName 字段名
    * @param fieldValue 字段值
    * @return
    * @throws Exception
    */
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{fieldName}/{fieldValue}")
    public JsonResult<InvoiceRegisterDetailVO> getDetailVOMapping(@PathVariable("fieldName") String fieldName, @PathVariable("fieldValue") String fieldValue) throws Exception {
        InvoiceRegisterDetailVO detailVO = invoiceRegisterService.getViewObject(fieldName, fieldValue, InvoiceRegisterDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
    * 创建资源对象数据
    * @param invoiceRegister
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<Serializable> createModelMapping(@RequestBody InvoiceRegisterDetailVO invoiceRegister) throws Exception {
        invoiceRegisterService.saveInvoiceRegister(invoiceRegister);
//        invoiceRegisterService.createEntity(invoiceRegister);
        return JsonResult.OK(invoiceRegister.getId());
    }

    /**
    * 根据id更新资源对象
    * @param invoiceRegister
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id")String id, @RequestBody InvoiceRegisterDetailVO invoiceRegister) throws Exception {
        invoiceRegisterService.updateInvoiceRegister(invoiceRegister);
//        invoiceRegisterService.updateEntity(invoiceRegister);
        return JsonResult.OK();
    }

    /**
    * 根据id删除资源对象
    * @param id
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = invoiceRegisterService.deleteDeliveryRegister(id);
//        boolean success = invoiceRegisterService.deleteEntity(id);
        log.debug("删除数据 开票登记:{} {}", id, success? "成功":"失败");
        return JsonResult.OK();
    }

    /**
    * 根据ids集合删除资源对象
    * @param ids
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = invoiceRegisterService.deleteDeliveryRegisterBatch(ids);
//        boolean success = invoiceRegisterService.deleteEntities(ids);
        log.debug("批量删除数据 开票登记:{} {}", ids, success? "成功":"失败");
        return JsonResult.OK();
    }

    private InvoiceFormExportModel convertToInvoiceFormExportModel(InvoiceFormVO invoiceFormVO) {
        InvoiceFormExportModel model = new InvoiceFormExportModel();
        // 进行属性赋值
        if (ObjectUtils.isNotEmpty(invoiceFormVO)){
            model.setSapContractCode(invoiceFormVO.getSapOrderCode())
                    .setSapOrderCode(invoiceFormVO.getSapOrderCode())
                    .setRemark(invoiceFormVO.getRemark());
        }
        if (ObjectUtils.isNotEmpty(invoiceFormVO.getProduct())){
            model.setAccountAssignmentLabel(ObjectUtils.isNotEmpty(invoiceFormVO.getProduct().getAccountAssignmentLabel())?invoiceFormVO.getProduct().getAccountAssignmentLabel().getLabel():"")
                    .setBusinessDept(invoiceFormVO.getProduct().getBusinessDept())
                    .setSalesTerritoryLabel(ObjectUtils.isNotEmpty(invoiceFormVO.getProduct().getSalesTerritoryLabel())?invoiceFormVO.getProduct().getSalesTerritoryLabel().getLabel():"")
                    .setProvince(invoiceFormVO.getProduct().getProvince())
                    .setCity(invoiceFormVO.getProduct().getCity())
                    .setSignerLabel(invoiceFormVO.getProduct().getSignerLabel())
                    .setContractType(invoiceFormVO.getProduct().getContractType())
                    .setContactCode(invoiceFormVO.getProduct().getContractCode())
                    .setRecipientLabel(invoiceFormVO.getProduct().getRecipientLabel())
                    .setProductName(invoiceFormVO.getProduct().getOrderModel())
                    .setOrderModel(invoiceFormVO.getProduct().getOrderModel())
                    .setSupportingMachineTool(invoiceFormVO.getProduct().getSupportingMachineTool())
                    .setProductPrice(invoiceFormVO.getProduct().getProductPrice())
                    .setProductSeries(invoiceFormVO.getProduct().getProductSeries())
                    .setGrade(invoiceFormVO.getProduct().getGrade())
                    .setMachineToolName(ObjectUtils.isNotEmpty(invoiceFormVO.getProduct().getMachineToolTypeLabel())?invoiceFormVO.getProduct().getMachineToolTypeLabel().getLabel():"")
                    .setFinalUser(invoiceFormVO.getProduct().getFinalUser());
        }
        return model;
    }

    public List<InvoiceFormExportModel> convertList(List<InvoiceFormVO> invoiceFormVOList) {
        return invoiceFormVOList.stream()
                .map(this::convertToInvoiceFormExportModel)
                .collect(Collectors.toList());
    }
    
}